package com.example.demoes.exception;

import com.example.demoes.result.BusinessResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@ControllerAdvice
public class BusinessExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public BusinessResponse globalException(HttpServletRequest request, HandlerMethod method, BusinessException ex) {
        log.info("GlobalExceptionHandler...");
        return BusinessResponse.fail(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public BusinessResponse globalException(HttpServletRequest request, HandlerMethod method, RuntimeException ex) {
        log.info("GlobalExceptionHandler...");
        return BusinessResponse.fail(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(ArithmeticException.class)
    public BusinessResponse processArithmeticException(HttpServletRequest request, HandlerMethod method, ArithmeticException exception) {
        if (log.isWarnEnabled()) {
            log.warn("ArithmeticException :", exception);
        }
        return BusinessResponse.fail(exception.getMessage());
    }
}
